package com.laker.autotest.core;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.laker.autotest.config.EasyConfig;
import com.laker.autotest.utils.TestNGUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
public class SendEmailListener extends TestListenerAdapter {
    final JavaMailSender javaMailSender = SpringUtil.getBean(JavaMailSender.class);
    final EasyConfig config = SpringUtil.getBean(EasyConfig.class);


    @Override
    public void onFinish(ITestContext testContext) {
        List<ITestResult> failedTests = getFailedTests();
        log.info("total case {}  个", getAllTestMethods().length);
        log.info("failed case {}  个", failedTests.size());
        log.info("passed case {}  个", getPassedTests().size());
        if (config.isSendEmail()) {
            sendHtmlMail();
            log.info("[SendEmaiFinish]");
        }
    }

    private void sendHtmlMail() {
        try {
            MimeMessage mimeMailMessage = javaMailSender.createMimeMessage();
            //true表示需要创建一个multipart message
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
            mimeMessageHelper.setFrom(config.getSenderEmail());
            mimeMessageHelper.setTo(config.getSendTo());
            mimeMessageHelper.setSubject(LocalDateTimeUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss") + " 自动化测试报告");
            String s = FileUtil.readString(new File(TestNGUtil.getReportDir(), TestNGUtil.getReportFileName()), StandardCharsets.UTF_8);
            mimeMessageHelper.setText(s, true);
            if (config.getTraceOptions().screenshotEnable) {
                List<ITestResult> failedTests = getFailedTests();
                failedTests.forEach(it -> {
                    File file = new File(TestNGUtil.getScreenShotPath(it));
                    if (file.exists()) {
                        try {
                            mimeMessageHelper.addAttachment(FileUtil.getName(file), file);
                        } catch (MessagingException e) {
                            log.error("Send html email addInline error!", e);
                        }
                    }
                });
            }
            javaMailSender.send(mimeMailMessage);
            log.info("Send html email success.");
        } catch (MessagingException e) {
            log.error("Send html email error!", e);
        }
    }

}
